﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Data;

namespace BPMS.Core
{
    public class DataRecordDynamic : DynamicObject
    {
        private IDataRecord dataRecord;
        public DataRecordDynamic(IDataRecord dataRecord)
        {
            this.dataRecord = dataRecord;
        }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            try
            {
                var index = dataRecord.GetOrdinal(binder.Name);
                if (dataRecord.IsDBNull(index))
                {
                    if (binder.ReturnType.IsValueType)
                    {
                        result = Activator.CreateInstance(binder.ReturnType);
                    }
                    else
                    {
                        result = null;
                    }
                }
                else
                {
                    var value = dataRecord.GetValue(index);
                    if (value.GetType() == binder.ReturnType)
                        result = value;
                    else
                        result = Convert.ChangeType(value, binder.ReturnType);
                }
                return true;
            }
            catch (Exception ex)
            {
                if (binder.ReturnType.IsValueType)
                {
                    result = Activator.CreateInstance(binder.ReturnType);
                }
                else
                {
                    result = null;
                }
                return false;
            }
        }
    }

    public class DataRowDynamic : DynamicObject
    {
        private readonly DataRow dataRow;

        public DataRowDynamic(DataRow dataRow)
        {
            this.dataRow = dataRow;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            try
            {
                var value = dataRow[binder.Name];
                if (DBNull.Value == value || value == null)
                {
                    if (binder.ReturnType.IsValueType)
                    {
                        result = Activator.CreateInstance(binder.ReturnType);
                    }
                    else
                    {
                        result = null;
                    }
                }
                else
                {
                    result = value;
                }
                return true;
            }
            catch (Exception ex)
            {
                if (binder.ReturnType.IsValueType)
                {
                    result = Activator.CreateInstance(binder.ReturnType);
                }
                else
                {
                    result = null;
                }
                return false;
            }
        }
    }
}
